<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>websocket通讯</title>
</head>

<script type="text/javascript">
    let websocket = null;

    function openSocket() {
        //判断当前浏览器是否支持WebSocket
        if ('WebSocket' in window) {
            let url = "http://localhost:8081/client/" + document.getElementById('userId').value;
            url = url.replace("https", "ws").replace("http", "ws");
            if (websocket == null) {
                websocket = new WebSocket(url);
            }

            //连接发生错误的回调方法
            websocket.onerror = function () {
                setMessageInnerHTML("error");
            };

            //连接成功建立的回调方法
            websocket.onopen = function (event) {
                console.log("websocket已打开");
            }

            //接收到消息的回调方法
            websocket.onmessage = function (event) {
                setMessageInnerHTML(event.data);
            }

            //连接关闭的回调方法
            websocket.onclose = function () {
                setMessageInnerHTML("close");
            }

            //监听窗口关闭事件，当窗口关闭时，主动去关闭websocket连接，防止连接还没断开就关闭窗口，server端会抛异常。
            window.onbeforeunload = function () {
                websocket.close();
            }

            //将消息显示在网页上
            function setMessageInnerHTML(innerHTML) {
                document.getElementById('message').innerHTML += innerHTML + '<br/>';
            }
        } else {
            console.log("您的浏览器不支持websocket!!!")
        }
    }

    //关闭连接
    function closeWebSocket() {
        if (websocket != null) {
            websocket.close();
            websocket = null;
        }
    }

    //发送消息
    function send() {
        const myId = document.getElementById('userId').value;
        const message = document.getElementById('text').value;
        const toUserId = document.getElementById('toUserId').value;
        websocket.send('{"发往":"' + toUserId + '","信息":"' + message + '"}');
        document.getElementById('message').innerHTML += '==>[' + toUserId + ']: ' + message + '<br/>';
    }
</script>
<body>
msg:<input id="text" type="text"/>
toUserId:<input id="toUserId" type="text"/>
userId:<input id="userId" type="text"/>
<p>【操作】：
    <button type="button" onclick="openSocket()">openSocket</button>
</p>
<p>【操作】：
    <button type="button" onclick="send()">发送消息</button>
</p>
<p>【操作】：
    <button type="button" onclick="closeWebSocket()">Close</button>
</p>

<div id="message"></div>

</body>
</html>